package com.qiniuyun.backai.controller;

import com.qiniuyun.backai.common.ErrorCode;
import com.qiniuyun.backai.common.PageResult;
import com.qiniuyun.backai.common.R;
import com.qiniuyun.backai.domain.vo.ConversationHistoryVO;
import com.qiniuyun.backai.domain.vo.MessageVO;
import com.qiniuyun.backai.exception.ThrowUtils;
import com.qiniuyun.backai.service.IConversationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;

import java.util.List;

/**
 * 会话控制器
 *
 * @author 王程楠
 * @since 2025-09-23
 */
@Slf4j
@RestController
@RequestMapping("/history/sessions")
@RequiredArgsConstructor
@Tag(name = "历史会话管理", description = "历史会话相关接口")
@Validated
public class ConversationController {
    private final IConversationService conversationService;

    /**
     * 历史会话列表
     */
    @GetMapping
    @Operation(summary = "历史会话列表", description = "分页查询用户的历史会话列表")
    public R<PageResult<ConversationHistoryVO>> getHistorySessions(
            @Parameter(description = "页码，从0开始", example = "0")
            @RequestParam(defaultValue = "0")
            @NotNull(message = "页码不能为空")
            @Min(value = 0, message = "页码不能小于0")
            Integer page,

            @Parameter(description = "每页记录数", example = "10")
            @RequestParam(defaultValue = "10")
            @NotNull(message = "每页记录数不能为空")
            @Min(value = 1, message = "每页记录数不能小于1")
            Integer size,

            @Parameter(description = "用户ID", example = "1001")
            @RequestParam(required = false)
            Long userId) {

        try {
            // 参数校验
            ThrowUtils.throwIf(page < 0, ErrorCode.PARAMS_ERROR, "页码不能小于0");
            ThrowUtils.throwIf(size < 1 || size > 100, ErrorCode.PARAMS_ERROR, "每页记录数必须在1-100之间");

            PageResult<ConversationHistoryVO> result = conversationService.getHistorySessions(page, size, userId);
            return R.ok(result);
        } catch (Exception e) {
            log.error("查询历史会话列表失败", e);
            return R.fail("查询历史会话列表失败");
        }
    }

    /**
     * 会话详情
     */
    @GetMapping("/{convId}/messages")
    @Operation(summary = "会话详情", description = "获取指定会话的消息列表")
    public R<List<MessageVO>> getSessionMessages(
            @Parameter(description = "会话ID", example = "5001")
            @PathVariable
            @NotNull(message = "会话ID不能为空")
            Long convId) {

        try {
            // 参数校验
            ThrowUtils.throwIf(convId == null || convId <= 0, ErrorCode.PARAMS_ERROR, "会话ID必须为正整数");

            List<MessageVO> messages = conversationService.getSessionMessages(convId);
            return R.ok(messages);
        } catch (Exception e) {
            log.error("查询会话详情失败，convId: {}", convId, e);
            return R.fail("查询会话详情失败");
        }
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/{convId}")
    @Operation(summary = "删除会话", description = "删除指定的会话记录")
    public R<Void> deleteSession(
            @Parameter(description = "会话ID", example = "5001")
            @PathVariable
            @NotNull(message = "会话ID不能为空")
            Long convId) {

        try {
            // 参数校验
            ThrowUtils.throwIf(convId == null || convId <= 0, ErrorCode.PARAMS_ERROR, "会话ID必须为正整数");

            boolean success = conversationService.deleteSession(convId);
            if (success) {
                return R.ok("对话记录删除成功", null);
            } else {
                return R.fail(404, "会话不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("删除会话失败，convId: {}", convId, e);
            return R.fail("删除会话失败");
        }
    }
}
